<?php


namespace app\index\controller;

use think\Db;
use think\exception\DbException;

/**
 * 数据库分页操作
 * Class DbPageTest
 * @package app\index\controller
 */
class DbPageTest
{
    /**
     * 查询第一页
     * @return \think\response\Json
     */
    public function page_test1()
    {
        try {
            $res = Db::table('t_user')
                ->field(['id,name'])
                ->limit(0, 2)
                ->select();
            return json(['msg' => '查询成功！', 'data' => $res]);
        } catch (DbException $e) {
            return json(['msg' => '查询失败！', 'data' => $e]);
        }
    }

    /**
     * 查询第二页
     * @return \think\response\Json
     */
    public function page_test2()
    {
        try {
            $res = Db::table('t_user')
                ->field(['id,name'])
                ->page(2, 2)
                ->select();
            return json(['msg' => '查询成功！', 'data' => $res]);
        } catch (DbException $e) {
            return json(['msg' => '查询失败！', 'data' => $e]);
        }
    }

    /**
     * 查询第三页
     * sql：SELECT id,name FROM `t_user` LIMIT 4,2
     * @return \think\response\Json
     */
    public function page_limit_test2()
    {
        try {
            $res = Db::table('t_user')
                ->field(['id,name'])
                ->limit(2)
                ->page(3)
                ->select();
            return json(['msg' => '查询成功！', 'data' => $res]);
        } catch (DbException $e) {
            return json(['msg' => '查询失败！', 'data' => $e]);
        }
    }

}